<template>
    <div class="permission-management">
        <div v-loading="loading" class="permission-tree-container">
            <span style="margin-bottom:1rem;">当前权限：
                <el-tag :type="role === 'admin' ? 'warning' : role === 'companyAdmin' ? 'success' : 'info'">{{
                    getRoleLabel(role)
                    }}</el-tag>
            </span>
            <el-tree ref="permissionTreeRef" :data="permissionStore.permissionTreeData" :props="defaultProps"
                show-checkbox node-key="code" default-expand-all :check-strictly="false">
                <template #default="{ node }">
                    <div class="permission-node">
                        <span>{{ node.label }}</span>
                    </div>
                </template>
            </el-tree>
        </div>
        <div class="actions">
            <el-button type="primary" @click="handleSave">保存权限设置</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { usePermissionStore } from '@/stores/permission'
import { getPermissionApi, getRoleApi, updatePermissionApi } from '@/api/auth';
import { handleError } from '@/utils/handleError';

const permissionStore = usePermissionStore()
const permissionTreeRef = ref(null)

const defaultProps = {
    children: 'children',
    label: 'label'
}

let props = defineProps(['userinfo'])
const role = ref(null)
const loading = ref(false)
const initializePermissionTree = async () => {
    try {
        loading.value = true
        let res = await getPermissionApi({
            id: props.userinfo.id
        })
        let roleRes = await getRoleApi({
            username: props.userinfo.username
        })
        role.value = roleRes.data[0]
        let permissions = res.data
        permissionTreeRef.value?.setCheckedKeys(permissions)
    } catch (error) {
        handleError(error)
    } finally {
        loading.value = false
    }
}

function getRoleLabel(role) {
    switch (role) {
        case 'admin':
            return '管理员'
        case 'companyAdmin':
            return '单位管理员'
        case 'normalUser':
            return '普通用户'
        default:
            return '未知角色'
    }
}

const handleSave = async () => {
    try {
        const checkedKeys = permissionTreeRef.value?.getCheckedKeys() || []
        const halfCheckedKeys = permissionTreeRef.value?.getHalfCheckedKeys() || []
        // 只获取叶子节点的权限
        const getLeafPermissions = (keys) => {
            return keys.filter(key => {
                const node = permissionTreeRef.value.getNode(key)
                return !node.childNodes || node.childNodes.length === 0
            })
        }
        const leafCheckedKeys = getLeafPermissions(checkedKeys)
        const leafHalfCheckedKeys = getLeafPermissions(halfCheckedKeys)
        const allLeafKeys = [...leafCheckedKeys, ...leafHalfCheckedKeys]
        await ElMessageBox.confirm(
            '确定要保存权限更改吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        await updatePermissionApi({
            user_id: props.userinfo.id,
            permissions: allLeafKeys
        })
        ElMessage.success('权限保存成功')
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('保存失败：' + error.message)
        }
    }
}
onMounted(() => {
    initializePermissionTree()
})
</script>


<style scoped>
.permission-management {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.permission-tree-container {
    flex: 1;
    overflow: auto;
    padding: 20px;
}

.actions {
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #dcdfe6;
    text-align: right;
}
</style>